/*
    Project:        Home Power Control
    File:           HPCSensor.cpp
    Author:         christian@karunamusic.at
    Date:           01.2015
    Description:    Baseclass for all sensors.
 */

#include <QTextStream>
#include "Logger/HPCLogger.h"
#include "HPCSensor.h"

HPCSensor::HPCSensor(TSensorType type, const QString& name, quint32 id , quint8 pin)
    : QObject(), m_Type(type), m_Name(name), m_ID(id), m_Pin(pin), m_MeasureUnit()
{
    connect( &m_Value, SIGNAL(changed(HPCValue&)), this, SLOT(ValueChanged(HPCValue&)) );
    connect( &m_Value, SIGNAL(alarmed(HPCSensorValue&, bool, unsigned int)), this, SLOT(ValueAlarmed(HPCSensorValue&, bool, unsigned int)) );
}

HPCSensor::~HPCSensor()
{
}

HPCSensor& HPCSensor::MeasureUnit( const QString& munit )
{
    m_MeasureUnit = munit;
    return *this;
}

QString HPCSensor::asString() const
{
    return Name() + " (Type " + QString::number((quint8)m_Type) + ", ID " + QString::number(m_ID) + ") on pin " + QString::number(m_Pin);
}

void HPCSensor::addAlarm( QString& Min, QString& Max )
{
    m_Value.addAlarm( Min,Max );
}

void HPCSensor::Measure()
{
    // do nothing
}

void HPCSensor::ValueChanged( HPCValue& val )
{
    if ( val.V() == m_Value.V() && val.TimeStamp() == m_Value.TimeStamp() )
    {
        LOG(debug, "sensor " << Name() << " changed: " << val.V().toString());
        emit changed( this, m_Value );
    }
}

void HPCSensor::ValueAlarmed( HPCSensorValue& val, bool gt, unsigned int ndx )
{
    if ( val.V() == m_Value.V() && val.TimeStamp() == m_Value.TimeStamp() )
    {
        LOG(debug, "sensor " << Name() << " alarmed: " << val.V().toString() << " (max: " << gt << ", ndx: " << ndx << ")");
        emit alarmed( this, m_Value, gt, ndx );
    }
}

void HPCSensor::setValue( HPCValue& val )
{
    m_Value = val;
}

QDataStream& operator<< ( QDataStream& os, const HPCSensor& s )
{
    os << (quint16)s.m_Type
       << s.m_Name
       << s.m_ID
       << s.m_Pin
       << s.m_MeasureUnit
       << s.m_Value;

    return os;
}
